<?php

namespace XWAM\Addon\POrgCustomer\Controller;

/**
 * 客户控制器
 *
 * @since 1.0 <2014-10-20> SoChishun <14507247@qq.com> Added.
 */
class CustomerController extends AddonbaseController {

    /**
     * 获取客户列表搜索数据
     * @return array
     * @since 1.0 2014-12-30 by sutroon
     */
    function customer_list_get_search() {
        $search = $_GET;
        if (!empty($search['telphone'])) {
            $where['telphone'] = array('like', '%' . $search['telphone'] . '%');
        }
        if (!empty($search['name'])) {
            $where['name'] = array('like', '%' . $search['name'] . '%');
        }
        if (!empty($search['user_name'])) {
            $where['user_name'] = $search['user_name'];
        }
        if (!empty($search['serial_no'])) {
            $where['serial_no'] = $search['sn'];
        }
        if (!empty($search['buy_count'])) {
            $where['buy_count'] = array('GT', $search['buy_count']);
        }
        if (!empty($search['total_amount'])) {
            $where['total_amount'] = array('GT', $search['total_amount']);
        }
        if (!empty($search['buy_time'])) {
            $where['buy_time'] = array('LT', $search['buy_time']);
        }
        if (!empty($search['create_time'])) {
            $where['create_time'] = array(array('LT', $search['create_time'] . ' 23:59:59'), array('GT', $search['create_time'] . ' 0:0:0'));
        }
        if ($this->user_login_data['type_name'] == 'SEAT') {
            $where['user_name'] = $this->loginData['user_name'];
        }
        $where['status'] = 1;
        return array('search' => $search, 'where' => $where);
    }

    // 客户列表
    public function customer_list() {
        $arrSearch = $this->customer_list_get_search();
        if (I('action') == 'export') {
            $M = M($arrSearch['table']);
            $afields = AddonD('CustomerAttr')->where(array('is_exportable' => 'Y'))->order('sort, id')->getField('field_name, title');
            $sfields = '';
            foreach ($afields as $field => $title) {
                if ($sfields) {
                    $sfields.=' ,';
                }
                $sfields.="$field as '$title'";
            }
            $list = $M->field($sfields)->where($arrSearch['where'])->select();
            if (!$list) {
                $this->error('找不到符合条件的记录!');
            }
            sofn_excel_export($list);
        } else {
            $afields = AddonD('CustomerAttr')->where(array('is_listable' => 'Y'))->order('sort, id')->getField('field_name, title');
            // 去除固定字段
            $diff = array('serial_no', 'name', 'telphone', 'sex', 'address');
            foreach ($diff as $key) {
                if (array_key_exists($key, $afields)) {
                    unset($afields[$key]);
                }
            }
            $anames = array_keys($afields);
            $list = D('Common')->get_paging_list($arrSearch['where'], $show, array('field' => implode(',', $anames), 'ORDERBY' => 'create_time desc', 'PAGEPARAMS' => $arrSearch['search'], 'TABLE' => 't_porg_customer'));
            $this->assign('searchlist', AddonD('CustomerAttr')->get_customer_search_list());
            $this->assign('page', $show);
            $this->assign('list', $list);
            $this->assign('afields', $afields);
            $this->assign('search', $arrSearch['search']);
            $this->display_cpp();
        }
    }

    // 检测电话号码是否重复 2015-1-2 by sutroon
    public function check_telphone($tel = '') {
        $count = 0;
        if (C('APPCONF.CUSTOMER_EDIT_TELPHONE_CHECK') && $tel) {
            $tel = ltrim($tel, '0');
            $count = AddonD('Customer')->where(array('telphone' => array('like', '%' . $tel)))->count();
        }
        $this->ajaxReturn(array('success' => $count < 1));
    }

    // 2016-1-21 SoChishun Added.
    public function customer_edit($id = 0, $tel = '') {
        // 自定义字段
        $fields = AddonD('CustomerAttr')->get_customer_require_list();
        $this->assign('fields', $fields);

        $where = array();
        if ($id) {
            $where['id'] = $id;
        }
        if ($tel) {
            $where['telphone'] = array('like', '%' . $tel); // 从后面匹配
        }
        $data = AddonD('Customer')->find_customer($where);
        if (!isset($data['telphone'])) {
            $data['telphone'] = $tel;
        }
        // 标题
        $meta_title = '新增客户';
        if ($tel) {
            $meta_title = '来电：' . $tel;
        } else if ($id) {
            $meta_title = '编辑 ' . $data['name'];
        }
        $this->assign('meta_title', $meta_title);
        $this->assign('data', $data);
        $this->display();
    }

    function customer_edit_save() {
        $result = AddonD('Customer')->save_customer();
        if ($result['status']) {
            $this->success('保存成功!', AddonU('customer_list'), 1);
        } else {
            $this->error($result['info'], '', 2);
        }
    }

    // 客户弹屏
    public function customer_popup() {
        $id = I('id');
        $params = new \Org\So\Params();
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('userID', 'number', '座席编号无效!');
        $params->addParam('serialNo', 'require', '客户编号无效!');
        $params->addParam('telphone', 'require', '联系电话未填写!');
        if ($params->hasError()) {
            $this->act_error($params->getError());
        }
        $params->addData('personalName');
        $params->addData('sex');
        $siteID = I('siteID');
        $telphone = I('telphone');
        $userID = I('userID');
        $personalName = I('personalName');
        $M = new \Think\Model\AdvModel('tcustomer');

        // 检测电话号码是否被占用
        if (C('APPCONF.CUSTOMER_EDIT_TELPHONE_CHECK')) {
            $existsData = $M->query("select personalName, userID, userName from vcustomer where telphone='$telphone' and siteID=$siteID");
            if ($existsData && (!$id || ($id && $existsData[0]['userID'] !== $userID))) {
                $this->act_error("[电话号码:$telphone / 姓名:" . $existsData[0]['personalName'] . "] 已归属座席:" . $existsData[0]['userName'] . "!", 5);
            }
        }

        // 扩展字段
        /*
          $list = sofunc_get_sys_exfield_list('CUSTOMER', $siteID);
          $exdata = $params->patchParams($list);
          if ($params->hasError()) {
          $this->act_error($params->getError());
          } */
        $zipCode = I('zipCode');
        $params->addData('idNo');
        $params->addData('remark');
        $params->addData('address');
        $params->addData('interested');
        // $params->addData('contactResults');
        $params->addData('tags');

        if ($id) {
            $params->addData('id', $id);
            $result = $M->save($params->getParams());
            if (false !== $result) {
                $sqls = false;
                if ($exdata) {
                    $str = '';
                    foreach ($exdata as $k => $v) {
                        $str.=",`$k`='$v' ";
                    }
                    if ($str) {
                        $str = substr($str, 1);
                    }
                    $sqls = "update tcustomer_ex_$siteID set $str where userID=$id;";
                    $M->execute($sqls);
                }
            }
        } else {
            $params->addData('state', 1);
            $params->addData('createdTime', date('Y-m-d h:i:s'));
            $result = $M->add($params->getParams());
            /*
              if (false !== $result) {
              $id = $result;
              $sqls = false;
              if ($exdata) {
              $sqls[] = "insert into tcustomer_ex_$siteID (userID, " . implode(',', array_keys($exdata)) . ") values ($id, '" . implode("','", array_values($exdata)) . "');";
              }
              // 新增客户的时候自动保存地址
              $address = AddressAction::split_cnregion(I('address'));
              if ($address && ($address[0] || $address[3])) {
              $sqls[] = "insert into tuser_address (userID, consignee, telphone, province, city, area, street, zipCode) values ($id, '$personalName', '$telphone', '" . $address[0] . "', '" . $address[1] . "', '" . $address[2] . "', '" . $address[3] . "', '$zipCode');";
              }
              if ($sqls) {
              $M->patchQuery($sqls);
              }
              } */
        }
        if ($result === false) {
            $this->act_error('保存失败');
        } else {
            if (C('APPCONF.CUSTOMER_EDIT_CLOSE_ON_SAVE')) {
                $this->act_close_dialog(true, '保存成功!');
            } else {
                $this->success('保存成功!', U('Customer/customer_edit', 'rp=1&id=' . $id));
            }
        }
    }

    // 客户物理删除 2014-12-25 by sutroon
    public function customer_delete($id = '') {
        $result = AddonD('Customer')->delete_customer($id);
        $this->dialogJump($result['status'], $result['info']);
    }

    // 客户加入回收站 2014-12-25 by sutroon
    public function customer_recycle($id = '') {
        $result = AddonD('Customer')->recycle_customer($id);
        $this->dialogJump($result['status'], $result['info']);
    }

    // 从回收站还原客户 2014-12-25 by sutroon
    public function restore_customer($id = '') {
        $result = AddonD('Customer')->restore_customer($id);
        $this->ajaxMsg($result, '还原%!');
    }

}
